<script setup lang="ts">
import { shelfRequestParams, RequestParams } from "@/api/standard/type";
import {
  BookshelfList,
  addBookshelf,
  delBookshelf,
  FormBookshelf,
  updateBookshelf,
  syncBook,
} from "@/api/standard/index";
import { BookshelfOptions } from "@/api/inventory/index";
import { LibraryOptions } from "@/api/library/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
// ================================================================================
// ref
const ruleFormRef = ref(); //弹框表单
const ids = ref([] as number[]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
let LibOptions = ref([] as any);
const ruleForm = ref({} as any);
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
} as any);
const tableList = ref([{}] as shelfRequestParams[]);

const shelfTotalLayer = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("书架总层数不能为空"));
  } else if (!/^\d+(\.\d+)?$/.test(value)) {
    callback(new Error("请输入有效的数字（可以是小数）"));
  } else {
    callback();
  }
};

const rules = reactive({
  libraryId: [
    { required: true, message: "请选择图书馆", trigger: "change" },
    // { min: 1, max: 5, message: "请输入1到5位", trigger: "blur" },
  ],
  shelfStandardName: [
    { required: true, message: "书架规格不能为空", trigger: "blur" },
    { min: 1, max: 30, message: "书架规格过长", trigger: "blur" },
  ],
  shelfFirstLayerHeight: [
    { required: true, message: "第一层距地高不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字", trigger: "blur" },
  ],

  shelfTotalLayer: [
    { required: true, message: "书架总层数不能为空", trigger: "change" },
    { validator: shelfTotalLayer, trigger: "change" },
  ],
  shelfTotalArrange: [
    { required: true, message: "书架总列数不能为空", trigger: "blur" },
    { pattern: /^\d+$/, message: "请输入有效的整数", trigger: "blur" },
  ],
  shelfArrangeWidth: [
    { required: true, message: "书架列宽不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字", trigger: "blur" },
  ],
});
// 挂载
onMounted(() => {
  handleQuery();
});
// ================================================================================

/**
 * 查询
 */
const handleQuery = async () => {
  try {
    loading.value = true;
    const res = await BookshelfList(queryParams);
    console.log(res, "res");

    tableList.value = res.data.records;

    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    // console.error(error);
    loading.value = false; // 将 loading 的值设置为 false，以便停止加载动画
  }
};
/**
 * 重置
 */
const resetQuery = () => {
  queryParams.shelfName = "";
  handleQuery();
};
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */

const bookshelfref = ref();
const Bookshelf = ref([] as any);
const ocrBookshelf = ref([] as any);
const openDialog = async (id?: number) => {
  Bookshelf.value = [];
  // ruleForm.value.rfidNearShelfList = [];
  // ruleForm.value.ocrNearShelfList = [];

  const res = await LibraryOptions(useStore.encryptedData);
  LibOptions.value = res.data;
  dialogVisible.value = true;
  // 先禁用校验
  ruleFormRef.value?.clearValidate();

  if (id) {
    const res = await FormBookshelf(id as any);
    ruleForm.value = res.data;
    const ress = await BookshelfOptions(res.data.libraryId as any);
    Bookshelf.value = ress.data;
    ocrBookshelf.value = ress.data;
    // 数据设置后再清除一次校验
    nextTick(() => {
      ruleFormRef.value?.clearValidate();
    });
    console.log(ruleForm.value, "ruleForm");
    title.value = "修改书架";
  } else {
    title.value = "新增书架";
    ruleFormRef.value?.resetFields(); // 确保新增时表单是干净的
  }
};

const change = async (e: any) => {
  Bookshelf.value = [];
  ruleForm.value.rfidNearShelfList = [];
  const ress = await BookshelfOptions(e);
  Bookshelf.value = ress.data;
  ocrBookshelf.value = ress.data;
  bookshelfref.value.clearValidate();
  // ocrNearShelfref.value.clearValidate();
  // console.log(ress.data, "Bookshelf");
};

/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleForm.value = {
    rfidNearShelfList: [],
    ocrNearShelfList: [],
  } as any;
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = ruleForm.value.id;
      loading.value = true;
      if (userId) {
        console.log(ruleForm.value, "编辑");
        updateBookshelf(ruleForm.value)
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("书架修改成功");
              close();
              handleQuery();
            } else {
              ElMessage.error(res.msg);
              close();
              handleQuery();
              loading.value = false;
            }
          })
          .finally(() => (loading.value = false));
      } else {
        //  console.log("新增");
        ruleForm.value.libraryId = useStore.user.libraryId;
        addBookshelf(ruleForm.value)
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("书架新增成功");
              close();
              handleQuery();
            } else {
              ElMessage.error(res.msg);
              close();
              handleQuery();
              loading.value = false;
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

/**
 * 删除
 */
const dell = (id: any) => {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    // console.log(Number(userIds), userIds);
    delBookshelf(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        handleQuery();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};
/**
 * 枚举
 */
const SidesStatus = (status: any) => {
  const STATUSES = [
    { id: 0, name: "单面书架" },
    { id: 1, name: "双面书架" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;

  handleQuery();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  handleQuery();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const twoSidesOptions = [
  { label: "单面书架", value: 0 },
  { label: "双面书架", value: 1 },
];
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize;
};
// 计算属性，返回已排序的 Bookshelf 数据源
// const sortedBookshelf = computed(() => {
//   return Bookshelf.value.slice().sort((a, b) => {
//     // 根据 label 的字符串大小比较
//     return a.label.localeCompare(b.label);
//   });
// });
// const ocrBookshelfList = computed(() => {
//   return ocrBookshelf.value.slice().sort((a, b) => {
//     // 根据 label 的字符串大小比较
//     return a.label.localeCompare(b.label);
//   });
// });

// 监听 formData.rfidNearShelfList 的变化，对其进行排序
// watch(
//   () => ruleForm.value.rfidNearShelfList,
//   (newValue) => {
//     if (newValue && Array.isArray(newValue)) {
//       //  添加空值检查
//       newValue.sort((a, b) => {
//         const labelA =
//           Bookshelf.value.find((item) => item.value === a)?.label || "";
//         const labelB =
//           Bookshelf.value.find((item) => item.value === b)?.label || "";
//         return labelA.localeCompare(labelB);
//       });
//     }
//   }
// );
// // 监听 formData.ocrNearShelfList 的变化，对其进行排序
// watch(
//   () => ruleForm.value.ocrNearShelfList,
//   (newValue) => {
//     if (newValue && Array.isArray(newValue)) {
//       newValue.sort((a, b) => {
//         const labelA =
//           ocrBookshelf.value.find((item) => item.value === a)?.label || "";
//         const labelB =
//           ocrBookshelf.value.find((item) => item.value === b)?.label || "";
//         return labelA.localeCompare(labelB);
//       });
//     }
//   }
// );
const Synchronize = async () => {
  try {
    await ElMessageBox.confirm("确认要同步书架吗?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    ElMessage.info("书架同步中，请稍候...");
    await syncBook(useStore.encryptedData);
    //ElMessage.success("数据同步成功");
  } catch {
    //ElMessage.error("数据同步失败，请重试");
  }
};
</script>

<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="550px"
      append-to-body
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
        status-icon
      >
        <el-form-item label="图书馆" prop="libraryId">
          <el-select
            style="width: 350px"
            v-model="ruleForm.libraryId"
            placeholder="请选择图书馆"
            @change="change"
          >
            <el-option
              v-for="item in LibOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="书架类型" prop="twoSides">
          <el-select
            style="width: 350px"
            v-model="ruleForm.twoSides"
            placeholder="请选择书架类型"
          >
            <el-option
              v-for="(status, index) in twoSidesOptions"
              :key="index"
              :label="status.label"
              :value="status.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="书架规格" prop="shelfStandardName">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfStandardName"
            placeholder="请输入书架规格名称"
          />
        </el-form-item>
        <el-form-item label="书架总层数" prop="shelfTotalLayer">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfTotalLayer"
            placeholder="请输入书架总层数"
          />
        </el-form-item>
        <el-form-item label="第一层距地高" prop="shelfFirstLayerHeight">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfFirstLayerHeight"
            placeholder="请输入书架第一层距地高"
          />
        </el-form-item>
        <el-form-item label="书架列宽" prop="shelfArrangeWidth">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfArrangeWidth"
            placeholder="请输入书架列宽"
          />
        </el-form-item>
        <el-form-item label="书架总列数" prop="shelfTotalArrange">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfTotalArrange"
            placeholder="请输入书架总列数"
          />
        </el-form-item>
        <el-form-item label="书架长度" prop="shelfLength">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfLength"
            placeholder="请输入书架长度"
          />
        </el-form-item>
        <el-form-item label="书架宽度" prop="shelfWidth">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfWidth"
            placeholder="请输入书架宽度"
          />
        </el-form-item>
        <el-form-item label="书架高度" prop="shelfHeight">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfHeight"
            placeholder="请输入书架高度"
          />
        </el-form-item>
        <el-form-item label="书架层高" prop="shelfLayerHeight">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfLayerHeight"
            placeholder="请输入书架层高"
          />
        </el-form-item>
        <el-form-item label="书架总层高" prop="shelfTotalLayerHeight">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfTotalLayerHeight"
            placeholder="请输入书架总层高"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="书架规格" prop="name">
          <el-input
            v-model="queryParams.shelfStandardName"
            placeholder="请输入书架规格"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="Search"
            >搜索</el-button
          >
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <el-button icon="Plus" type="success" @click="openDialog()"
          >新增</el-button
        >
        <el-button type="warning" style="margin-left: 10px" @click="Synchronize"
          >同步书架</el-button
        >
        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="Delete"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <!--  <el-table-column type="selection" width="55" align="center" /> > -->
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column
          label="书架规格"
          prop="shelfStandardName"
          align="center"
        />
        <el-table-column
          label="书架列宽"
          prop="shelfArrangeWidth"
          align="center"
        />
        <el-table-column
          label="书架总列数"
          prop="shelfTotalArrange"
          align="center"
        />
        <el-table-column label="书架类型" prop="twoSides" :align="'center'">
          <template #default="{ row }">
            {{ SidesStatus(row.twoSides) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog(row.id)"
              icon="Edit"
              >编辑</el-button
            >
            <el-button
              type="primary"
              link
              size="small"
              @click="dell(row.id)"
              icon="Delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
